from django.contrib.auth.backends import ModelBackend
import re
from . models import  User
def get_user_by_username(account):

    try:
        # 判断account内部保存的是否是手机号
        if re.match('^1[3-9]\d{9}$',account):
            # 进入内部是手机号
            user=User.objects.get(mobile=account)
        else:
            # 是用户名
            user=User.objects.get(username=account)
    except Exception as e:
        return None
    else:
        return user

class UsernameMobileAuthenBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):

        user=get_user_by_username(username)
        if user and user.check_password(password):
            return user